﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using System.Web.Http;
using System.Web.Http.Cors;
using FFSupplier.Common.Helper;
using System.Text.RegularExpressions;
using System.Net.Http.Headers;

namespace FFSupplier.Common.TKCommon
{
    public static class CommonFunction
    {
        public static string Serialize<T>(T t)
        {
            string XmlString = "";
            XmlWriterSettings settings = new XmlWriterSettings();
            //去除xml声明
            //settings.OmitXmlDeclaration = true;
            settings.Indent = true;
            settings.Encoding = Encoding.Default;
            using (System.IO.MemoryStream mem = new MemoryStream())
            {
                using (XmlWriter writer = XmlWriter.Create(mem, settings))
                {
                    //去除默认命名空间xmlns:xsd和xmlns:xsi
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    ns.Add("", "");
                    XmlSerializer formatter = new XmlSerializer(t.GetType());
                    formatter.Serialize(writer, t, ns);
                }
                XmlString = Encoding.Default.GetString(mem.ToArray());
            }
            return XmlString;

            //  XNamespace
            //XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            //ns.Add("", "");
            //using (StringWriter sw = new StringWriter())
            //{
            //    XmlSerializer xz = new XmlSerializer(t.GetType());                
            //    xz.Serialize(sw, t, ns);
            //    return sw.ToString();
            //}
        }
        public static T Deserialize<T>(T t, string s)
        {
            using (StringReader sr = new StringReader(s))
            {
                XmlSerializer xz = new XmlSerializer(t.GetType());

                return (T)xz.Deserialize(sr);
            }
        }
        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <param name="fromHours">距离当前时间多少小时，默认为0</param>
        /// <returns></returns>
        public static long GetTimestamp(int fromHours=0)
        {
            TimeSpan ts = DateTime.Now.ToUniversalTime().AddHours(fromHours) - new DateTime(1970, 1, 1);//ToUniversalTime()转换为标准时区的时间,去掉的话直接就用北京时间
            return (long)ts.TotalMilliseconds; //精确到毫秒
        }

        /// <summary>  
        /// 将c# DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time">时间</param>  
        /// <returns>long</returns>  
        public static long ConvertDateTimeToInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
            return t;
        }
    }
    public static class APConfig
    {
        public static string crmApiUrlBase = ConfigurationManager.AppSettings["crmApiUrlBase"];
        public static string crmApiDomain = ConfigurationManager.AppSettings["crmApiDomain"];
        public static string crmApiUser = ConfigurationManager.AppSettings["crmApiUser"];
        public static string crmApiPassword = ConfigurationManager.AppSettings["crmApiPassword"];

        public static string   YunAPPid= ConfigurationManager.AppSettings["appId"];
        public static string YunSecret = ConfigurationManager.AppSettings["secret"];
        public static string DanbaoSecret = ConfigurationManager.AppSettings["DanbaoSecret"];
        public static string DanBaoAppId = ConfigurationManager.AppSettings["DanBaoAppId"];
        public static string eid = ConfigurationManager.AppSettings["eid"];
        public static string DanBaoformCodeId= ConfigurationManager.AppSettings["DanBaoformCodeId"];
        public static string ProjectCodeId = ConfigurationManager.AppSettings["ProjectCodeId"];
        public static string MarketCodeId = ConfigurationManager.AppSettings["MarketCodeId"];
        public static string BatchDebatCodeId = ConfigurationManager.AppSettings["BatchDebatCodeId"];
        public static string CustomerDebatCodeId = ConfigurationManager.AppSettings["CustomerDebatCodeId"];
        public static string RebateCodeId = ConfigurationManager.AppSettings["RebateCodeId"];
        public static string PricePolicy = ConfigurationManager.AppSettings["PricePolicy"];
        public static string SalesOrder = ConfigurationManager.AppSettings["SalesOrder"];
        public static string key = ConfigurationManager.AppSettings["key"];

    }
   
    /// <summary>
    /// crm webapi返回接口异常处理
    /// </summary>
    public class CrmHttpResponseException : System.Exception
    {
        #region Properties
        private static string _stackTrace;
        /// <summary>
        /// Gets a string representation of the immediate frames on the call stack.
        /// </summary>
        public override string StackTrace
        {
            get { return _stackTrace; }
        }

        #endregion Properties
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the CrmHttpResponseException class.
        /// </summary>
        /// <param name="content">The populated HTTP content in Json format.</param>

        public CrmHttpResponseException(HttpContent content) : base(ExtractMessageFromContent(content)) { }


        /// <summary>
        /// Initializes a new instance of the CrmHttpResponseException class.
        /// </summary>
        /// <param name="content">The populated HTTP content in Json format.</param>
        /// <param name="innerexception">The exception that is the cause of the current exception,or a null reference
        /// if no innerexception is specified.</param>

        public CrmHttpResponseException(HttpContent content, Exception innerexception) : base(ExtractMessageFromContent(content), innerexception) { }

        #endregion Constructors
        #region Methods
        /// <summary>
        /// Extracts the CRM specific error message and stack trace from an HTTP content. 
        /// </summary>
        /// <param name="content">The HTTP content in Json format.</param>
        /// <returns>The error message.</returns>


        private static string ExtractMessageFromContent(HttpContent content)
        {
            string message = String.Empty;
            string downloadedContent = content.ReadAsStringAsync().Result;
            if (content.Headers.ContentType.MediaType.Equals("text/plain"))
            {
                message = downloadedContent;
            }
            else if (content.Headers.ContentType.MediaType.Equals("application/json"))
            {
                JObject jcontent = (JObject)JsonConvert.DeserializeObject(downloadedContent);
                IDictionary<string, JToken> d = jcontent;

                // An error message is returned in the content under the 'error' key. 

                if (d.ContainsKey("error"))
                {
                    JObject error = (JObject)jcontent.Property("error").Value;
                    message = (String)error.Property("message").Value;
                }
                else if (d.ContainsKey("Message"))
                    message = (String)jcontent.Property("Message").Value;
                if (d.ContainsKey("StackTrace"))
                    _stackTrace = (String)jcontent.Property("StackTrace").Value;
            }
            else if (content.Headers.ContentType.MediaType.Equals("text/html"))
            {
                message = "HTML content that was returned is shown below.";
                message += "\n\n" + downloadedContent;
            }
            else
            {
                message = String.Format("No handler is available for content in the {0} format.", content.Headers.ContentType.MediaType.ToString());
            }
            return message;
            #endregion Methods
        }
    }




    public  class CrmAction
    {
        public string accesstoken = "";
        public HttpClient GetHttpClientWithCredential()
        {
            HttpClient httpClient = new HttpClient();

            if (APConfig.crmApiUrlBase.Contains("https"))
            {
                httpClient.BaseAddress = new Uri("https://tcsw.tcsw.com.cn/api/data/v9.0/");
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                var tokencontent = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string,string>("client_id","ea1d02b9-3cbb-4bc7-b109-31ac1805c57f"),
                new KeyValuePair<string,string>("client_secret","OWRfTWozPgwPEyIPQkr2ErYPh1bJ_zrIUfrHSAZl"),
                new KeyValuePair<string,string>("resource","https://tcsw.tcsw.com.cn/api/data/v9.0/"),
                new KeyValuePair<string,string>("username",@"tcsw\crmadmin"),
                new KeyValuePair<string,string>("password","Teconphi@123"),
                new KeyValuePair<string,string>("grant_type","password"),
                         });
                var res = httpClient.PostAsync("https://adfs.tcsw.com.cn/adfs/oauth2/token", tokencontent);
                var respo = res.Result.Content.ReadAsStringAsync().Result;
                accesstoken = JObject.Parse(respo).GetValue("access_token").ToString();

               httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accesstoken);
            }
            else
            {
                 httpClient = new HttpClient(new HttpClientHandler()
                {
                    Credentials = new NetworkCredential(APConfig.crmApiUser, APConfig.crmApiPassword, APConfig.crmApiDomain)
                });
                //Specify the Web API address of the service and the period of time each request 
                // has to execute.
                //httpClient.BaseAddress = new Uri(_configuration.orgUrl());
                httpClient.Timeout = new TimeSpan(0, 2, 0);  //2 minutes
                httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                //  httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
                // httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
                httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=\"*\"");
                //   httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", "b59f39a6-03b9-e911-84db-e94e2aa2ba42");
                //Send the WhoAmI request to the Web API using a GET request. 
            }


            return httpClient;

        }
        
        public async Task<string> createNRelationShip(string targetEntityName, string targetEntityId, string relatedEntityName, string relatedTargetId, string relatedName)
        {
            string result=string.Empty;
            Dictionary<string, object> dic = new Dictionary<string, object>();
            string weburi = APConfig.crmApiUrlBase;

            dic.Add("@odata.id", weburi + targetEntityName  + "(" + targetEntityId.Replace("{", "").Replace("}", "") + ")");

            using (HttpClient httpClient = GetHttpClientWithCredential())
            {
                HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("POST"), weburi + relatedName + "(" + relatedTargetId + ")/" + relatedEntityName + "/$ref");
                request.Content = new StringContent(JsonConvert.SerializeObject(dic), Encoding.UTF8, "application/json");

                //禁止异步操作
                //远程获取数据
                var task = httpClient.SendAsync(request);
                var rep = task.Result;//在这里会等待task返回。
                if (rep.IsSuccessStatusCode)
                {
                   result = rep.Content.ReadAsStringAsync().Status.ToString();
                    //guid = new Guid(accountUri.Substring(accountUri.Length - 37, 36));
                }
                else
                {
                    var errorMsg = rep.Content.ReadAsStringAsync();
                    var er = new CrmHttpResponseException(rep.Content);
                    result = er.Message;

                }
            }
            return result;
        }

        
       
        public async Task<string> deleteNRelationShip(string targetEntityName, string targetEntityId, string relatedEntityName, string relatedTargetId, string relatedName)
        {
            string result = string.Empty;
            string weburi = APConfig.crmApiUrlBase;
            weburi = weburi + relatedName + "(" + relatedTargetId.Replace("{", "").Replace("}", "") + ")/" + relatedEntityName + "/$ref?$id=" + weburi + targetEntityName + "(" + targetEntityId.Replace("{", "").Replace("}", "") + ")";
            using (HttpClient httpClient = GetHttpClientWithCredential())
            {
                //禁止异步操作
                //远程获取数据
                var task = httpClient.DeleteAsync(weburi);
                var rep = task.Result;//在这里会等待task返回。
                if (rep.IsSuccessStatusCode)
                {
                    result = rep.Content.ReadAsStringAsync().Status.ToString();
                    //guid = new Guid(accountUri.Substring(accountUri.Length - 37, 36));
                }
                else
                {
                    var errorMsg = rep.Content.ReadAsStringAsync();
                    var er = new CrmHttpResponseException(rep.Content);
                    result = er.Message;

                }
                //result = httpClient.DeleteAsync(weburi);
                //string resultContent = result.Content.ReadAsStringAsync();

            }
            return result;
        }

       
        public async Task< string>  deleteRecord(string guid, string entityName)
        {
           
            string resultContent;
            string weburi = APConfig.crmApiUrlBase + entityName + "(" + guid.Replace("{", "").Replace("}", "") + ")";
            using (HttpClient httpClient = GetHttpClientWithCredential())
            {
                var   result = await httpClient.DeleteAsync(weburi);
                resultContent = await result.Content.ReadAsStringAsync();
            }
            return resultContent;
        }
         
        public async Task<string> retrieveMultipleByFilter(string entityNames,   string user)
        {
            string result = "";
            string webApiUrl = APConfig.crmApiUrlBase + entityNames; 
            using (HttpClient httpClient = GetHttpClientWithCredential())
            {
                httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", user);
                try
                {
                    httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                    HttpResponseMessage response = await httpClient.GetAsync(webApiUrl);
                    result = await response.Content.ReadAsStringAsync();
                }
                catch (Exception e)
                {
                    throw e;
                } 
            }
            return result;
        }

        public async Task<JArray> retrieveMultiplePageing(string uri, string count, JArray jArray)
        {
            var result = "";

            using (HttpClient httpClient = GetHttpClientWithCredential())
            {
                httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue,odata.maxpagesize=" + count);
                HttpResponseMessage response = await httpClient.GetAsync(uri);
                result = await response.Content.ReadAsStringAsync();

                JObject jObject = (JObject)JsonConvert.DeserializeObject(result.ToString());

                if (((JArray)jObject["value"]).Count > 0)
                {
                    jArray.Add(jObject.SelectToken("value"));
                }

                if (result.ToString().Contains("@odata.nextLink"))
                {
                    await retrieveMultiplePageing(((JArray)jObject["@odata.nextLink"]).ToString(), count, jArray);
                }
            }
            return jArray;
        }

       
        public async Task<string> retrieveRecord(string guid, string entityNames, string xName)
        {
            string result = "";
            string weburi = APConfig.crmApiUrlBase + entityNames + "(" + guid.Replace("{", "").Replace("}", "") + ")";
            if (!string.IsNullOrEmpty(xName))
            {
                weburi = weburi + xName;
            }
            using (HttpClient httpClient = GetHttpClientWithCredential())
            {
                try
                {
                    httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                    HttpResponseMessage response = await httpClient.GetAsync(weburi);
                    result = await response.Content.ReadAsStringAsync();
                }
                catch (Exception ex)
                {

                    throw;
                }

            }
            return result;
        }
 
        
        public async Task<string> retrieveMultiple(string entityNames)
        {
            string result = "";

            string webApiUrl = APConfig.crmApiUrlBase + entityNames;
            using (HttpClient httpClient = GetHttpClientWithCredential())
            {


                try
                {
                    httpClient.DefaultRequestHeaders.Add("Prefer", "odata.maxpagesize=10,odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                    
                    //禁止异步操作
                    //远程获取数据
                    var task = httpClient.GetAsync(webApiUrl);
                    var rep = task.Result;//在这里会等待task返回。

                    //读取响应内容
                    var task2 = rep.Content.ReadAsStringAsync();
                    result = task2.Result;//在这里会等待task返回。

                }
                catch (Exception ex)
                {

                    throw;
                }

            }
            return result;
        }

        public async Task<Guid> createRecord(string entityobject, string entityNames, string user)
        {
            Guid guid = Guid.Empty;
            string createUrl = string.Format(APConfig.crmApiUrlBase + entityNames);
            var createStr = entityobject;
            var content = new StringContent(createStr, Encoding.UTF8, "application/json");

            using (HttpClient _httpClient = GetHttpClientWithCredential())
            { 
                _httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", user);
                //禁止异步操作
                //远程获取数据
                var task = _httpClient.PostAsync(createUrl, content);
                var rep = task.Result;//在这里会等待task返回。
                if (rep.IsSuccessStatusCode)
                {
                    string accountUri = rep.Headers.GetValues("OData-EntityId").FirstOrDefault();
                    guid = new Guid(accountUri.Substring(accountUri.Length - 37, 36));
                }
                else
                {
                    var errorMsg = rep.Content.ReadAsStringAsync();
                    var er = new CrmHttpResponseException(rep.Content);
                    string ss = er.Message;
                    throw new Exception(ss);
                }
                //读取响应内容
                //var task2 = rep.Content.ReadAsStringAsync();
                //var result = task2.Result;//在这里会等待task返回。

            }
            return guid;
        }

        public  Guid createRecords(string entityobject, string entityNames)
        {
            Guid guid = Guid.Empty;
            string createUrl = string.Format(APConfig.crmApiUrlBase + entityNames);
            var createStr = entityobject;
            var content = new StringContent(createStr, Encoding.UTF8, "application/json");           
            
            using (HttpClient client = GetHttpClientWithCredential())
            {
                
                //禁止异步操作
                //远程获取数据
                var task = client.PostAsync(createUrl, content);
                var rep = task.Result;//在这里会等待task返回。
                if(rep.IsSuccessStatusCode)
                {
                    string accountUri = rep.Headers.GetValues("OData-EntityId").FirstOrDefault();
                    guid = new Guid(accountUri.Substring(accountUri.Length - 37, 36));
                }
                else
                {
                    var errorMsg = rep.Content.ReadAsStringAsync();
                    var er = new CrmHttpResponseException(rep.Content);
                     
                    throw   er;
                    //throw new Exception(createStr + errorMsg);
                }
                //读取响应内容
                //var task2 = rep.Content.ReadAsStringAsync();
                //var result = task2.Result;//在这里会等待task返回。

            }
            return guid;
        }
        public Guid createRecordsforuser(string entityobject, string entityNames,string user)
        {
            Guid guid = Guid.Empty;
            string createUrl = string.Format(APConfig.crmApiUrlBase + entityNames);
            var createStr = entityobject;
            var content = new StringContent(createStr, Encoding.UTF8, "application/json");
            HttpClient _httpClient = new HttpClient();

            if (createUrl.Contains("https"))
            {
                _httpClient.BaseAddress = new Uri("https://tcsw.tcsw.com.cn/");
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                _httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                _httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                var tokencontent = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string,string>("client_id","ea1d02b9-3cbb-4bc7-b109-31ac1805c57f"),
                new KeyValuePair<string,string>("client_secret","OWRfTWozPgwPEyIPQkr2ErYPh1bJ_zrIUfrHSAZl"),
                new KeyValuePair<string,string>("resource","https://tcsw.tcsw.com.cn/api/data/v9.0/"),
                new KeyValuePair<string,string>("username",@"tcsw\crmadmin"),
                new KeyValuePair<string,string>("password","Teconphi@123"),
                new KeyValuePair<string,string>("grant_type","password"),
                         });
                var res = _httpClient.PostAsync("https://adfs.tcsw.com.cn/adfs/oauth2/token", tokencontent);
                var respo = res.Result.Content.ReadAsStringAsync().Result;
                var accesstoken = JObject.Parse(respo).GetValue("access_token").ToString();
                _httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accesstoken);
                //_httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", user);
            }
            else
            {
                _httpClient = GetHttpClientWithCredential();
            }

            using (_httpClient)
            {
                _httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", user);
                //禁止异步操作
                //远程获取数据
                var task = _httpClient.PostAsync(createUrl, content);
                var rep = task.Result;//在这里会等待task返回。
                if (rep.IsSuccessStatusCode)
                {
                    string accountUri = rep.Headers.GetValues("OData-EntityId").FirstOrDefault();
                    guid = new Guid(accountUri.Substring(accountUri.Length - 37, 36));
                }
                else
                {
                    var errorMsg = rep.Content.ReadAsStringAsync();
                    var er = new CrmHttpResponseException(rep.Content);
                    string ss = er.Message;
                    throw new Exception(ss);
                }
                //读取响应内容
                //var task2 = rep.Content.ReadAsStringAsync();
                //var result = task2.Result;//在这里会等待task返回。

            }
            return guid;
        }

        public async Task<Guid> CreateRecodeByUserid(string entityobject, string entityNames, string user)
        {
            Guid guid = Guid.Empty;
            string createUrl = string.Format(APConfig.crmApiUrlBase + entityNames);
            var createStr = entityobject;
            var content = new StringContent(createStr, Encoding.UTF8, "application/json");
            HttpClient _httpClient = new HttpClient();

            if (createUrl.Contains("https"))
            {
                _httpClient.BaseAddress = new Uri("https://tcsw.tcsw.com.cn/");
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                _httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                _httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                var tokencontent = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string,string>("client_id","ea1d02b9-3cbb-4bc7-b109-31ac1805c57f"),
                new KeyValuePair<string,string>("client_secret","OWRfTWozPgwPEyIPQkr2ErYPh1bJ_zrIUfrHSAZl"),
                new KeyValuePair<string,string>("resource","https://tcsw.tcsw.com.cn/api/data/v9.0/"),
                new KeyValuePair<string,string>("username",@"tcsw\crmadmin"),
                new KeyValuePair<string,string>("password","Teconphi@123"),
                new KeyValuePair<string,string>("grant_type","password"),
                         });
                var res = _httpClient.PostAsync("https://adfs.tcsw.com.cn/adfs/oauth2/token", tokencontent);
                var respo = res.Result.Content.ReadAsStringAsync().Result;
                var accesstoken = JObject.Parse(respo).GetValue("access_token").ToString();
                _httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accesstoken);
                //_httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", user);
            }
            else
            {
                _httpClient = GetHttpClientWithCredential();
            }

            using (_httpClient)
            {
                _httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", user);
                //禁止异步操作
                //远程获取数据
                HttpResponseMessage task = await _httpClient.PostAsync(createUrl, content);
                
                if (task.IsSuccessStatusCode)
                {
                    string accountUri = task.Headers.GetValues("OData-EntityId").FirstOrDefault();
                    guid = new Guid(accountUri.Substring(accountUri.Length - 37, 36));
                }
                else
                { 
                    var er = new CrmHttpResponseException(task.Content); 
                    throw er;
                } 
            }
            return guid;
        }
        public async Task<string> retrieveRecordByFechXml(string fetchxml)
        {
            string result = "";
            string webApiUrl = APConfig.crmApiUrlBase;
            webApiUrl = webApiUrl + fetchxml;
            using (HttpClient httpClient = GetHttpClientWithCredential())
            {
                httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
 
                HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, webApiUrl);
                //  _httpClient.SendAsync(req)
                var task = httpClient.SendAsync(req);
                var rep = task.Result;//在这里会等待task返回。
                var ex = new CrmHttpResponseException(rep.Content);
                //读取响应内容
                var task2 = rep.Content.ReadAsStringAsync();
                result = task2.Result;//在这里会等待task返回。

              
                result = task2.Result;//在这里会等待task返回。
            }
            return result;
        }
        public async Task<string> retrieveRecordByFechXmlforuser(string fetchxml,string user)
        {
            string result = "";
            string webApiUrl = APConfig.crmApiUrlBase;
            webApiUrl = webApiUrl + fetchxml;
            if (webApiUrl.Contains("https"))
            {
                HttpClient _httpClient = new HttpClient();
                _httpClient.BaseAddress = new Uri(APConfig.crmApiUrlBase);
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                _httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                _httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                var content = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string,string>("client_id","ea1d02b9-3cbb-4bc7-b109-31ac1805c57f"),
                new KeyValuePair<string,string>("client_secret","OWRfTWozPgwPEyIPQkr2ErYPh1bJ_zrIUfrHSAZl"),
                new KeyValuePair<string,string>("resource","https://tcsw.tcsw.com.cn/api/data/v9.0/"),
                new KeyValuePair<string,string>("username",@"tcsw\crmadmin"),
                new KeyValuePair<string,string>("password","Teconphi@123"),
                new KeyValuePair<string,string>("grant_type","password"),
                         });
                var res = _httpClient.PostAsync("https://adfs.tcsw.com.cn/adfs/oauth2/token", content);
                var respo = res.Result.Content.ReadAsStringAsync().Result;
                var accesstoken = JObject.Parse(respo).GetValue("access_token").ToString();
                //var myUri = new Uri(webApiUrl);
                //var myWebRequest = WebRequest.Create(myUri);
                //var myHttpWebRequest = (HttpWebRequest)myWebRequest;
                //myHttpWebRequest.PreAuthenticate = true;
                //myHttpWebRequest.Headers.Add("Authorization", "Bearer " + accesstoken);
                _httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accesstoken);
                _httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                _httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", user);
                //myHttpWebRequest.Accept = "application/json";
                //myHttpWebRequest.Headers.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");


                try
                {
                    HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, webApiUrl);
                  //  _httpClient.SendAsync(req)
                    var task =  _httpClient.SendAsync(req);
                    var rep = task.Result;//在这里会等待task返回。
                   // var ex = new CrmHttpResponseException(rep.Content);
                    //读取响应内容
                    var task2 = rep.Content.ReadAsStringAsync();
                    result = task2.Result;//在这里会等待task返回。

                    //using (HttpWebResponse myWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse())
                    //{
                    //    StreamReader read = new StreamReader(myWebResponse.GetResponseStream());
                    //    result = read.ReadToEnd();
                    //    myWebResponse.Close();
                    //}
                }
                catch (Exception e)
                {
                    result = @"{'@odata.context':'','value':[ ]}";                  
                }
            }
            else
            {
                using (HttpClient httpClient = GetHttpClientWithCredential())
                {

                    httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                    //httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", user);
                    //禁止异步操作
                    //远程获取数据
                    HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, webApiUrl);
                    req.Headers.Add("MSCRMCallerID", user);
                    var task =  httpClient.SendAsync(req);
                    var rep = task.Result;//在这里会等待task返回。
                    var ex = new CrmHttpResponseException(rep.Content);
                    //读取响应内容
                    var task2 = rep.Content.ReadAsStringAsync();
                    result = task2.Result;//在这里会等待task返回。
                }
            }
            return result;
             
        }
        public async Task<string> updateRecordforuser(string guid, string entityObject, string entityNames, string user)
        {
            string result = "";
            string weburi = APConfig.crmApiUrlBase + entityNames + "(" + guid.Replace("{", "").Replace("}", "") + ")";
            HttpRequestMessage uptReq = new HttpRequestMessage(new HttpMethod("PATCH"), weburi);
            var updateContent = entityObject; 
            uptReq.Content = new StringContent(updateContent, Encoding.UTF8, "application/json");

            using (HttpClient httpClient = GetHttpClientWithCredential())
            {

                httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", user);
                //禁止异步操作
                //远程获取数据
                var task =   httpClient.SendAsync(uptReq);
                var rep = task.Result;//在这里会等待task返回。

                //读取响应内容
                var task2 = rep.Content.ReadAsStringAsync();
                result = task2.Result;//在这里会等待task返回。
                result = rep.IsSuccessStatusCode.ToString();
                if (result == "False")
                {
                    var ex = new CrmHttpResponseException(rep.Content);
                    throw ex;
                }              
            }           
            return result; 
        }

        public async Task<string> PathRecode(string guid, string entityObject, string entityNames, string user)
        {
            string result = "";
            string idStr = "";
            HttpMethod httpMethod;
            if (!string.IsNullOrEmpty( guid))
            {
                idStr = "(" + guid.Replace("{", "").Replace("}", "") + ")";
                httpMethod = new HttpMethod("Patch");
            }
            else
            {
                httpMethod=new HttpMethod("POST");
            }
            string weburi = APConfig.crmApiUrlBase + entityNames + idStr;
            HttpRequestMessage uptReq = new HttpRequestMessage(httpMethod, weburi);
            HttpClient httpClient = new HttpClient();          
            var updateContent = entityObject;
            uptReq.Content = new StringContent(updateContent, Encoding.UTF8, "application/json");
            using (httpClient =GetHttpClientWithCredential())
            {

             //  httpClient.DefaultRequestHeaders.Add("MSCRMCallerID", user);
                //禁止异步操作
                //远程获取数据
                var task = await httpClient.SendAsync(uptReq);
                var rep = task;//在这里会等待task返回。

                //读取响应内容
                var task2 = rep.Content.ReadAsStringAsync();
                result = task2.Result;//在这里会等待task返回。
                result = rep.IsSuccessStatusCode.ToString();
                if (result == "False")
                {
                    var ex = new CrmHttpResponseException(rep.Content);
                    throw ex;
                }
                string responseUrl = rep.Headers.GetValues("OData-EntityId").FirstOrDefault();
                result = Regex.Replace(responseUrl, @"(.*\()(.*)(\).*)", "$2");
            }
           
            return result; 
        }

        public async Task<string> updateRecords(string guid, string entityObject, string entityNames)
        {
            string result = "";
            string weburi = APConfig.crmApiUrlBase + entityNames + "(" + guid.Replace("{", "").Replace("}", "") + ")";
            HttpRequestMessage uptReq = new HttpRequestMessage(new HttpMethod("PATCH"), weburi);

            var updateContent = entityObject;

            uptReq.Content = new StringContent(updateContent, Encoding.UTF8, "application/json");
            using (HttpClient httpClient = GetHttpClientWithCredential())
            {
                //禁止异步操作
                //远程获取数据
                var task = httpClient.SendAsync(uptReq);
                var rep = task.Result;//在这里会等待task返回。

                //读取响应内容
                var task2 = rep.Content.ReadAsStringAsync();
                result = task2.Result;//在这里会等待task返回。
                result = rep.IsSuccessStatusCode.ToString();
                if (result == "False")
                {
                    var ex = new CrmHttpResponseException(rep.Content);
                    throw ex;
                }
            }
            return result;
        }
    }
}